//
//  MineViewController.swift
//  StoryDemo
//
//  Created by mac on 2019/6/28.
//  Copyright © 2019年 zhkj. All rights reserved.
//

import UIKit
import PPBadgeViewSwift

class MineViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
    var tableview:UITableView!
    var userinfo:UserInfoResult!//商城用户信息
    var userOfxgy:UserOfxgy!//西瓜鱼用户信息
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell=tableView.dequeueReusableCell(withIdentifier: "re", for: indexPath) as!MineTableViewCell
        cell.selectionStyle = .none
        cell.one_view.layer.cornerRadius=5
        cell.two_view.layer.cornerRadius=5
        cell.three_view.layer.cornerRadius=5
        cell.four_view.layer.cornerRadius=5
        cell.five_view.layer.cornerRadius=30
        cell.avator.layer.cornerRadius=25
        
        if (userinfo != nil&&userOfxgy != nil) {
            cell.lb_unlogin.isHidden=true
            cell.name.isHidden=false
            cell.lb_nick.text=userinfo.Nick
            cell.lb_phone.text=userinfo.CellPhone
            cell.lb_coupon_count.text=userinfo.Counpon
            cell.lb_collec_count.text=userinfo.FavoriteProduct
            cell.lb_fav_count.text="\(userinfo.FavoriteShop)"
            cell.lb_visit_count.text="\(userinfo.HistoryVisitCount)"
            cell.avator.setImage(path: URL.init(string: userinfo.Photo!)!)
            cell.lb_coin.text="\(userOfxgy.Con)"
            
            cell.usv_dfk.pp.addBadge(number: Int(userinfo.WaitingForPay!)!)
            cell.usv_dfh.pp.addBadge(number: userinfo.WaitingForDelivery)
            cell.usv_dsh.pp.addBadge(number: Int(userinfo.WaitingForRecieve!)!)
            cell.usv_dpj.pp.addBadge(number: Int(userinfo.WaitingForComments!)!)
            cell.usv_sh.pp.addBadge(number: userinfo.RefundOrders)
            
            cell.usv_dfk.pp.moveBadge(x: -20, y: 0)
            cell.usv_dfh.pp.moveBadge(x: -20, y: 0)
            cell.usv_dsh.pp.moveBadge(x: -20, y: 0)
            cell.usv_dpj.pp.moveBadge(x: -20, y: 0)
            cell.usv_sh.pp.moveBadge(x: -20, y: 0)
            //        cell.usv_dfk.pp.setBadge(height: 25)
            //        cell.usv_dfk.pp.badgeView.font=UIFont.systemFont(ofSize: 10)
        }else{
            cell.lb_unlogin.isHidden=false
            cell.name.isHidden=true
            
            cell.lb_coupon_count.text="0"
            cell.lb_collec_count.text="0"
            cell.lb_fav_count.text="0"
            cell.lb_visit_count.text="0"
            cell.avator.image=UIImage(named: "default_avator")
            cell.lb_coin.text="0.00"
            
            cell.usv_dfk.pp.hiddenBadge()
            cell.usv_dfh.pp.hiddenBadge()
            cell.usv_dsh.pp.hiddenBadge()
            cell.usv_dpj.pp.hiddenBadge()
            cell.usv_sh.pp.hiddenBadge()
        }
        
        cell.avator.addOnClickListener(target: self, action: #selector(info))
        cell.name.addOnClickListener(target: self, action: #selector(info))
        cell.uv_setting.addOnClickListener(target: self, action: #selector(setting))
        cell.uv_msg.addOnClickListener(target: self, action: #selector(info))
        cell.usv_coupon.addOnClickListener(target: self, action: #selector(coupon))
        cell.usv_collection.addOnClickListener(target: self, action: #selector(collection))
        cell.usv_fav_shop.addOnClickListener(target: self, action: #selector(fav_shop))
        cell.usv_visit.addOnClickListener(target: self, action: #selector(visit))
        cell.usv_wallet.addOnClickListener(target: self, action: #selector(wallet))
        cell.usv_zhsf.addOnClickListener(target: self, action: #selector(zhsf))
        cell.usv_dfk.addOnClickListener(target: self, action: #selector(dfk_order))
        cell.usv_dfh.addOnClickListener(target: self, action: #selector(dfh_order))
        cell.usv_dsh.addOnClickListener(target: self, action: #selector(dsh_order))
        cell.usv_dpj.addOnClickListener(target: self, action: #selector(dpj_order))
        cell.usv_sh.addOnClickListener(target: self, action: #selector(info))//售后
        cell.see_all_view.addOnClickListener(target: self, action: #selector(all_order))//查看全部工单
        cell.three_view.addOnClickListener(target: self, action: #selector(xgyorder))//查看服务工单
        cell.uv_service.addOnClickListener(target: self, action: #selector(service))//官方客服
        cell.uv_join.addOnClickListener(target: self, action: #selector(join))//商家入驻
        cell.uv_join2.addOnClickListener(target: self, action: #selector(join2))//成为师傅
        cell.uv_join3.addOnClickListener(target: self, action: #selector(join3))//赚西瓜币
        return cell
    }
    @objc func join2(){
        let popview = ZXPopView.init(frame: self.view.bounds)
        let shareview=Bundle.main.loadNibNamed("ShareView", owner: nil, options: nil)?[0]as!ShareView
        QRCodeUtil.setQRCodeToImageView(shareview.uv_code, "https://sj.qq.com/myapp/detail.htm?apkName=com.ying.administrator.masterappdemo")
        shareview.layer.cornerRadius=10
        shareview.lb_desc.text="扫描下载师傅端APP，成为师傅"
        shareview.lb_desc.font=UIFont.systemFont(ofSize: 12)
        shareview.btn_ok.setTitle("立即下载", for: UIControl.State.normal)
        shareview.btn_ok.setTitleColor(UIColor.white, for: UIControl.State.normal)
        shareview.btn_ok.backgroundColor = .red
        shareview.btn_ok.layer.cornerRadius=5
        shareview.btn_ok.snp.makeConstraints { (make) in
            make.width.equalTo(100)
            make.height.equalTo(30)
        }
        popview.contenView = shareview
        popview.anim = 0
        popview.contenView!.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.equalTo(screenW-60)
            make.height.equalTo(shareview.width)
        }
        popview.showInWindow()
    }
    @objc func join3(){
        UserID="18767773654"
        let popview = ZXPopView.init(frame: self.view.bounds)
        let shareview=Bundle.main.loadNibNamed("ShareView", owner: nil, options: nil)?[0]as!ShareView
        QRCodeUtil.setQRCodeToImageView(shareview.uv_code, "http://admin.xigyu.com/sign?phone=" + UserID! + "&type=8")
        shareview.layer.cornerRadius=10
        shareview.lb_desc.text="扫描加入西瓜鱼商城"
        shareview.lb_desc.font=UIFont.systemFont(ofSize: 12)
        shareview.btn_ok.setTitle("立即分享", for: UIControl.State.normal)
        shareview.btn_ok.setTitleColor(UIColor.white, for: UIControl.State.normal)
        shareview.btn_ok.backgroundColor = .red
        shareview.btn_ok.layer.cornerRadius=5
        shareview.btn_ok.snp.makeConstraints { (make) in
            make.width.equalTo(100)
            make.height.equalTo(30)
        }
        popview.contenView = shareview
        popview.anim = 0
        popview.contenView!.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.width.equalTo(screenW-60)
            make.height.equalTo(shareview.width)
        }
        popview.showInWindow()
    }
    func checkLogin() {
        if userkey==nil{
            self.navigationController?.pushViewController(LoginViewController(), animated: true)
            return
        }
    }
    @objc func join() {
        checkLogin()
        self.navigationController?.pushViewController(UIWebViewViewController(headtitle: "商家入驻", url: "http://mall.xigyu.com/m-weixin/shopregister/step1"), animated: true)
    }
    @objc func setting() {
        checkLogin()
        self.navigationController?.pushViewController(SettingViewController(), animated: true)
    }
    @objc func wallet() {
        checkLogin()
        self.navigationController?.pushViewController(WalletViewController(), animated: true)
    }
    @objc func coupon() {
        checkLogin()
        self.navigationController?.pushViewController(CouponViewController(index: 0), animated: true)
    }
    @objc func collection() {
        checkLogin()
        self.navigationController?.pushViewController(CollectionViewController(), animated: true)
    }
    @objc func fav_shop() {
        checkLogin()
        self.navigationController?.pushViewController(Fav_shopViewController(), animated: true)
    }
    @objc func visit() {
        checkLogin()
        self.navigationController?.pushViewController(VisitViewController(), animated: true)
    }
    @objc func service() {
        //创建UIAlertController(警告窗口)
        let alert = UIAlertController(title: "提示", message: "是否拨打电话给客服", preferredStyle: .alert)
        //创建UIAlertController(动作表单)
//        let alertB = UIAlertController(title: "Information", message: "sub title", preferredStyle: .actionSheet)
        //创建UIAlertController的Action
        let OK = UIAlertAction(title: "确定", style: .default) { (UIAlertAction) in
            // phoneStr:  电话号码
            let phone = "tel://" + "18767773654"
            if UIApplication.shared.canOpenURL(URL(string: phone)!) {
                UIApplication.shared.openURL(URL(string: phone)!)
            }
        }
        let Cancel = UIAlertAction(title: "取消", style: .cancel) { (UIAlertAction) in
            print("you selected cancel")
        }
        //将Actiont加入到AlertController
        alert.addAction(OK)
        alert.addAction(Cancel)
        //以模态方式弹出
        self.present(alert, animated: true, completion: nil)
        
    }
    @objc func info() {
        self.navigationController?.pushViewController(LoginViewController(), animated: true)
    }
    @objc func xgyorder() {
        self.navigationController?.pushViewController(XgyOrderViewController(index: 0), animated: true)
    }
    @objc func zhsf() {
        checkLogin()
        self.navigationController?.pushViewController(SendOrderViewController(), animated: true)
    }
    @objc func all_order() {
        checkLogin()
        self.navigationController?.pushViewController(OrderViewController(index: 0), animated: true)
    }
    @objc func dfk_order() {
        checkLogin()
        self.navigationController?.pushViewController(OrderViewController(index: 1), animated: true)
    }
    @objc func dfh_order() {
        checkLogin()
        self.navigationController?.pushViewController(OrderViewController(index: 2), animated: true)
    }
    @objc func dsh_order() {
        checkLogin()
        self.navigationController?.pushViewController(OrderViewController(index: 3), animated: true)
    }
    @objc func dpj_order() {
        checkLogin()
        self.navigationController?.pushViewController(OrderViewController(index: 4), animated: true)
    }
    func initTable(){
        tableview=UITableView(frame: CGRect(x: 0, y:0, width: screenW, height: screenH),style:.plain)
        
//        tableview.rowHeight = screenH-(self.tabBarController?.tabBar.frame.height)!
        tableview.backgroundColor="#F2F2F2".color()
        tableview.dataSource=self
        tableview.delegate=self
        tableview.separatorStyle = .none
        tableview.contentInset=UIEdgeInsets(top: -kStatusBarHeight, left: 0, bottom: kStatusBarHeight, right: 0)
        tableview.register(UINib (nibName: "MineTableViewCell", bundle: nil), forCellReuseIdentifier: "re")
        
        //refresh
        let header = TTRefreshHeader.init(refreshingBlock: {[weak self] in
            guard let strongSelf = self else{return}
            strongSelf.tableview.mj_header.endRefreshing()
            if userkey != nil {
               strongSelf.loadData()
            }
        })
        
        tableview.mj_header = header;
        
        self.view.addSubview(tableview)
    }
    func loadData(){
//        let userkey=UserDefaults.standard.string(forKey: "UserKey")
        var d = ["userkey":userkey,
                 "app_key":app_key,
                 "timestamp":getTimestamp()
            ] as! [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        AlamofireHelper.get(url: UserCenter_GetUser, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            ss.userinfo=UserInfoResult.init(json: res)
            ss.getUserInfoList()
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    func getUserInfoList(){
        let d = ["UserID":UserID,
                 "limit":"1"
            ] as! [String : String]
        AlamofireHelper.post(url: GetUserInfoList, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            if res["Info"] == "HTTP请求不合法，请求有可能被篡改"{
                return
            }
            ss.userOfxgy=res["Data"]["data"].arrayValue.compactMap({ UserOfxgy(json: $0)})[0]
            ss.tableview.reloadData()
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor="#F2F2F2".color()
        initTable()
        if userkey != nil {
            loadData()
        }
        NotificationCenter.default.addObserver(self, selector: #selector(logout), name: NSNotification.Name("logout"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(loginOk), name: NSNotification.Name("loginOk"), object: nil)
        // Do any additional setup after loading the view.
    }
    @objc func logout(){
        userinfo=nil
        userOfxgy=nil
        tableview.reloadData()
    }
    @objc func loginOk(){
        loadData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
